package com.zijing2333.adaptivescheduling.SwitcherManager.client;

import android.util.Log;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

public  class SocketClient implements Runnable{

    //TAG标记
    static final String TAG = "fun_SocketClient";

    private final String mIp;
    //端口号
    private final int mPort;

    //客户端端的回调
    private ClientCallback mCallback;

    private ClientConnectServerThread clientConnectServerThread;

    public static SocketClient launch(String ip, int port, ClientCallback callback){
        SocketClient socketClient = new SocketClient(ip,port,callback);
        new Thread(socketClient).start();
        return socketClient;
    }
    public SocketClient(String ip, int port,ClientCallback callback) {
        this.mIp = ip;
        this.mPort = port;
        this.mCallback = callback;
    }

    /**
     * 关闭连接
     */
    public void closeConnect() {
        if (clientConnectServerThread != null){
            clientConnectServerThread.close();
        }
        Log.d(TAG, "关闭连接");
    }



    /**
     * 发送数据到客户端方式3：String类型   采用的是DataOutputStream了
     * @param data
     */
    //直接调用clientConnectServerThread中写好的发送数据给服务端的方法即可，类型是String
    public void writeString(String ServiceName,String type,String data){
        if (clientConnectServerThread !=null){
            clientConnectServerThread.writeString(ServiceName,type,data);
        }else{
            Log.d(TAG, "clientConnectServerThread===null");
        }
    }

    @Override
    public void run() {
        try {
            Socket socket=new Socket(mIp,mPort);
            Log.d(TAG, "客户端Socket创建成功");
            clientConnectServerThread = new ClientConnectServerThread(socket, mCallback);
            new Thread(clientConnectServerThread).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
